/**
 * 接口请求封装
 * 支持 get post
 */
import config from './host'

const request = (url, options) => {
  uni.showLoading({
    title: '加载中...',
  })
  return new Promise((resolve, reject) => {
      uni.request({
        url: config.baseUrl+`${url}`,
        method: options.method,
        header: {
            'Content-Type': 'application/json; charset=UTF-8',
            'Authorization': uni.getStorageSync('token')   
        },
        data: options.method == 'GET' ? options.data : JSON.stringify(options.data),
        success: res => {
          const { statusCode } = res
          if (statusCode === 200) {
            const { errCode, errMsg } = res.data
            if (errCode !== 10000) {
              uni.showToast({
                title: errMsg || '信息有误',
                icon: 'error',
                duration: 2000
              })
            }
            resolve(res.data)
          } else {
            // 可以用switch根据code判断显示不同的信息提示
            let errMsg = statusCode == 404 ? '路径有误' : '信息有误'
            uni.showToast({
              title: errMsg,
              icon: 'error',
              duration: 2000
            })
          }
        uni.hideLoading()

        },
        fail: err => {
          reject(err)
          uni.hideLoading()
        }
      })
  })
}

const get = (url, option = {}) => {
  return request(url, {
    method: 'GET',
    data: option
  })
}

const post = (url, option = {}) => {
  return request(url, {
    method: 'POST',
    data: option
  })
}
export default {
   get,
   post
 }